package com.chenglong.supermarket.product.service.impl;

import com.chenglong.supermarket.common.constant.ProductConstant;
import com.chenglong.supermarket.common.to.SkuHasStockVo;
import com.chenglong.supermarket.common.to.es.SkuEsModel;
import com.chenglong.supermarket.common.utils.R;
import com.chenglong.supermarket.product.entity.*;
import com.chenglong.supermarket.product.feign.SearchFeginService;
import com.chenglong.supermarket.product.feign.WareFeginService;
import com.chenglong.supermarket.product.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenglong.supermarket.common.utils.PageUtils;
import com.chenglong.supermarket.common.utils.Query;

import com.chenglong.supermarket.product.dao.SpuInfoDao;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    AttrService attrService;
    @Autowired
    WareFeginService wareFeginService;
    @Autowired
    SearchFeginService searchFeginService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //组装数据
        ArrayList<SkuEsModel> upProducts = new ArrayList<>();
        //查询sku可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttr = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = baseAttr.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        HashSet<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttr.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //todo 发送远程调用是否有库存
        R r = null;
        Map<Long, Boolean> hasStockMap = null;
        try {
            r = wareFeginService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> SkuHasStockVos =(List<SkuHasStockVo>) r.get("data");
            hasStockMap = SkuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
        }


        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntityList.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //设置库存信息
            if (finalHasStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalHasStockMap.get(skuEsModel.getSkuId()));
            }
            //热度评分，暂时不做默认0
            skuEsModel.setHotScore(0l);
            //查询品牌和分类的名字
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatelogId());
            skuEsModel.setCatelogId(categoryEntity.getCatId());
            skuEsModel.setCatalogImg(categoryEntity.getIcon());
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        //发送给search服务存入es
        R r1 = searchFeginService.productStatusUp(skuEsModels);
        //根据r1的返回值，来判断是否成功
        //如果成功 更改数据库状态为上架
        baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SUP_UP);

        //todo 如果没成功，进行重试调用一次，接口幂等性，重试机制
        //Fegin客户端就有重试机制，该逻辑不必在自己写 默认是关闭状态
    }

}